#include "stdafx.h"
#include "HistoryIndicatorArbitrage.h"
#include "DataManager.hpp"
#include "HistoryLayout.h"
#include "KLineArbitrage.h"

CHistoryIndicatorArbitrage::CHistoryIndicatorArbitrage(SGHandle owner_handle) : CHistoryIndicatorBase(owner_handle)
{
}

CHistoryIndicatorArbitrage::~CHistoryIndicatorArbitrage()
{
	if(m_pArbitrageData) {
		m_pArbitrageData->onDataUpdate.disconnect(boost::bind(&CHistoryIndicatorArbitrage::OnDataUpdate, this));
	}
}

BOOL CHistoryIndicatorArbitrage::OnSGInitContext( SGContext* context_param )
{
	m_nArbitrageGoods = context_param->lparam;
	m_nArbitrageType = context_param->param1;
	m_nArbitrageCalcType = context_param->param2;

	return FALSE;
}

BOOL CHistoryIndicatorArbitrage::OnSGGoodsChange( SGGoodsChange* goods_change_param )
{
	CPeriodType period(goods_change_param->period_type, goods_change_param->period_param);

	CHistoryData::Key main_goods_key(goods_change_param->goods, period);
	m_pData = CDataManager<CHistoryData>::Instance()->GetData(main_goods_key);

	CHistoryData::Key key(m_nArbitrageGoods, period);

	if(m_pArbitrageData && key == m_pArbitrageData->m_tKey) {
		return FALSE;
	}

	if(m_pArbitrageData) {
		m_pArbitrageData->onDataUpdate.disconnect(boost::bind(&CHistoryIndicatorArbitrage::OnDataUpdate, this));
	}

	m_pArbitrageData = CDataManager<CHistoryData>::Instance()->GetData(key);
	m_pArbitrageData->onDataUpdate.connect(boost::bind(&CHistoryIndicatorArbitrage::OnDataUpdate, this));

	CHistoryIndicator* indicator_ptr = (CHistoryIndicator*)owner_handle_;
	uint64_t valid_begin_time = indicator_ptr->GetView()->GetLayout()->GetValidBeginTime();
	m_pArbitrageData->LoadDataByRange(valid_begin_time);

	return FALSE;
}

BOOL CHistoryIndicatorArbitrage::OnSGDrawBack( SGCanvas* canvas_param )
{
	CKLineArbitrage kline;
	CHistoryIndicator* indicator_ptr = (CHistoryIndicator*)owner_handle_;
	CAxes& axes = indicator_ptr->GetAxes();

	kline.SetType(m_nArbitrageType, m_nArbitrageCalcType);
	kline.SetData(m_pData, m_pArbitrageData);
	kline.Draw(axes, canvas_param);

	return FALSE;
}

BOOL CHistoryIndicatorArbitrage::OnSGDrawFore( SGCanvas* canvas_param )
{
	return FALSE;
}

BOOL CHistoryIndicatorArbitrage::OnSGSyncData( SGRange<uint64_t>* range_param )
{
	m_pArbitrageData->SyncDataByRange(range_param->begin, range_param->end);

	return FALSE;
}

void CHistoryIndicatorArbitrage::OnDataUpdate()
{
	CHistoryIndicator* indicator_ptr = (CHistoryIndicator*)owner_handle_;
	indicator_ptr->GetView()->GetLayout()->UpdateBack();
}
